package mr.ali.videoapp.portal.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import mr.ali.videoapp.portal.Bo.LoginBO;
import mr.ali.videoapp.portal.mapper.OpenIdMapper;
import mr.ali.videoapp.portal.model.CollectionUserMony;
import mr.ali.videoapp.portal.model.CollectionUserMonyIncome;
import mr.ali.videoapp.portal.model.OpenId;
import mr.ali.videoapp.portal.service.ICollectionUserMonyIncomeService;
import mr.ali.videoapp.portal.service.ICollectionUserMonyService;
import mr.ali.videoapp.portal.service.IOpenIdService;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author Mr-ali
 * @since 2024-08-01
 */
@Service
@Slf4j
public class OpenIdServiceImpl extends ServiceImpl<OpenIdMapper, OpenId> implements IOpenIdService {

    private final String userImg = "https://ikran-1329659431.cos.ap-guangzhou.myqcloud.com/icon/logo.jpg";
    @Resource
    OpenIdMapper openIdMapper;
    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private IOpenIdService openIdService;

    @Resource
    private ICollectionUserMonyIncomeService collectionUserMonyIncomeService;
    /**
     * 根据登录信息获取用户的OpenID
     *
     * @param loginBO 登录信息对象
     * @return 返回包含OpenID的字符串
     * @throws IOException 如果请求失败，则抛出IOException异常
     */
    private Integer userId = 111250;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public OpenId getOpenId(LoginBO loginBO) throws IOException {

        // 定义AppID
        // AppID
        String appId = "wx68b7ece486eb3e32";
        // 定义密钥
        // 密钥
        String secret = "d64374fdafaca0a7275dd96b19bf2c68";
        // 获取登录信息中的code
        // code
        String code = loginBO.getCode();
        Integer shareUserId = loginBO.getShareUserId();

        // 构造请求URL
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appId
                + "&secret=" + secret + "&js_code=" + code + "&grant_type=authorization_code";

        // 创建OkHttpClient对象
        // 客户端
        OkHttpClient client = new OkHttpClient();

        // 使用url发起请求
        // 用url发起请求
        Request request = new Request.Builder().url(url).build();

        // 执行请求并获取响应
        // 拿到响应
        Response response = client.newCall(request).execute();

        // 定义变量存储响应体内容
        String body = null;
        OpenId cont = null;
        // 如果响应成功
        // 如果响应成功，打印返回值
        if (response.isSuccessful()) {
            body = response.body().string();

            // 注意：这里的解析方式是不安全的，建议使用JSON解析库来处理
            // 解析sessionKey
            // 解析返回结果中的sessionKey和openId
            String sessionKey = body.split(":")[1].split(",")[0].replace(",", "");
            sessionKey = sessionKey.substring(1, sessionKey.length() - 1);
            // 解析openId
            String openId = body.split(":")[2].split(",")[0].replace("}", "");
            openId = openId.substring(1, openId.length() - 1);

            // 根据openId查询数据库中的OpenId对象
            cont = openIdMapper.selectByOpenId(openId);
//         用户信息缓存到redis中
//            redisTemplate.opsForValue().set("cont", cont);
            // 如果查询结果为空，则创建新的OpenId对象
            if (cont == null) {
                userId++;
                if (shareUserId != null && shareUserId != 0) {
                    openIdService.updateNotMoney(shareUserId, 0.3, true , "");
                }
                log.info("openId不存在，开始插入");
                // 创建OpenId对象并设置属性值
                // 如果不存在，则插入新的记录
                OpenId open = new OpenId()
                        .setOpenId(openId)
                        .setSessionId(sessionKey)
                        .setGmtCreate(System.currentTimeMillis())
                        .setStatus(1)
                        .setYesMoney(0.0)
                        .setNotMoney(0.0)
                        .setStatusCreate(System.currentTimeMillis() + 259200000)
                        .setUsername("ArTv" + userId)
                        .setUserImg(userImg);
                // 插入OpenId对象到数据库中
                openIdMapper.insert(open);
                log.info("openId插入成功");
                cont = openIdMapper.selectByOpenId(openId);
                // 用户信息缓存到redis中
//                redisTemplate.opsForValue().set("cont", cont);
                // 返回查询到的ElasticOpenId对象
                return cont;

            }


            // 返回查询到的ElasticOpenId对象
            return cont;
        }

        // 响应失败，返回null
        return null;
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public OpenId getOpenIdIkran(LoginBO login) throws IOException {

        // 定义AppID
        // AppID
        String appId = "wx5ffab93af68faef7";
        // 定义密钥
        // 密钥
        String secret = "2337814fb2241030c2b01bf7f2bb39e7";
        // 获取登录信息中的code
        // code
        String code = login.getCode();

        // 构造请求URL
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appId
                + "&secret=" + secret + "&js_code=" + code + "&grant_type=authorization_code";

        // 创建OkHttpClient对象
        // 客户端
        OkHttpClient client = new OkHttpClient();

        // 使用url发起请求
        // 用url发起请求
        Request request = new Request.Builder().url(url).build();

        // 执行请求并获取响应
        // 拿到响应
        Response response = client.newCall(request).execute();
        log.info("请求成功的数据", response.body().string());

        // 定义变量存储响应体内容
        String body = null;
        OpenId cont = null;
        // 如果响应成功
        // 如果响应成功，打印返回值
        if (response.isSuccessful()) {
            body = response.body().string();

            // 注意：这里的解析方式是不安全的，建议使用JSON解析库来处理
            // 解析sessionKey
            // 解析返回结果中的sessionKey和openId
            String sessionKey = body.split(":")[1].split(",")[0].replace(",", "");
            sessionKey = sessionKey.substring(1, sessionKey.length() - 1);
            // 解析openId
            String openId = body.split(":")[2].split(",")[0].replace("}", "");
            openId = openId.substring(1, openId.length() - 1);

            // 根据openId查询数据库中的OpenId对象
            cont = openIdMapper.selectByOpenId(openId);
//         用户信息缓存到redis中
            redisTemplate.opsForValue().set("cont", cont);
            // 如果查询结果为空，则创建新的OpenId对象
            if (cont == null) {
                userId++;
                log.info("openId不存在，开始插入");
                // 创建OpenId对象并设置属性值
                // 如果不存在，则插入新的记录
                OpenId open = new OpenId()
                        .setOpenId(openId)
                        .setSessionId(sessionKey)
                        .setGmtCreate(System.currentTimeMillis())
                        .setNotMoney(0.0)
                        .setYesMoney(0.0)
                        .setStatus(1)
                        .setStatusCreate(System.currentTimeMillis() + 259200000)
                        .setUsername("ArTv" + userId)
                        .setUserImg(userImg);
                // 插入OpenId对象到数据库中
                openIdMapper.insert(open);
                log.info("openId插入成功");
                cont = openIdMapper.selectByOpenId(openId);
                // 用户信息缓存到redis中
                redisTemplate.opsForValue().set("cont", cont);
                // 返回查询到的ElasticOpenId对象
                return cont;

            }


            // 返回查询到的ElasticOpenId对象
            return cont;
        }

        // 响应失败，返回null
        return null;
    }

    /**
     * 会员身份变成非会员
     */
    @Override
    public Integer deleteStatus(Integer id, Integer status) {
        Integer integer = openIdMapper.deleteStatus(id, status);
        return integer;
    }

    /**
     * 获取所有的用户
     */
    @Override
    public List<OpenId> getAllOpenId() {
        QueryWrapper<OpenId> queryWrapper = new QueryWrapper<>();
        List<OpenId> query = openIdMapper.selectList(queryWrapper);
        return query;
    }

    /**
     * 非会员身份变成会员
     */
    @Override
    public Integer updateOpenId(Integer id, Integer status, Long statusCreate) {
        Integer integer = 0;
        Long index = openIdMapper.selectById(id).getStatusCreate();
        if (index < System.currentTimeMillis()) {
            integer = openIdMapper.updateStatus(id, status, statusCreate);
            return integer;
        } else {
            statusCreate = index + (statusCreate - System.currentTimeMillis());
            integer = openIdMapper.updateStatusJia(id, status, statusCreate);
            return integer;
        }
    }


    /**
     * 用户语言跳换
     */
    @Override
    public Integer UpLanguage(Integer id, Integer language) {
        Integer integer = openIdMapper.upLanguage(id, language);
        return integer;
    }

    @Resource
    private ICollectionUserMonyService collectionUserMonyService;
    /**
     * 更新用户推广费用
     */
    @Override
    public void updateNotMoney(Integer id, Double money, Boolean close,String channel) {
        Double index = openIdMapper.selectById(id).getNotMoney();
        Double yesIndex = openIdMapper.selectById(id).getYesMoney();
        if (close) {
            money = index + money;
            openIdMapper.updateNotMoney(id, money);
            CollectionUserMonyIncome income = new CollectionUserMonyIncome();
            income.setUserId(id)
                    .setMoney(money)
                    .setGmtCreate(System.currentTimeMillis())
                    .setChannel(money > 0.5 ? "引导购买会员奖励" : "引导新用户奖励");
            collectionUserMonyIncomeService.insertCollectionUserMonyIncome(income);
        }
        if (!close) {
            CollectionUserMony income = new CollectionUserMony();
            income.setMoney(money)
                    .setUserId(id)
                    .setChannel(channel)
                    .setGmtCreate(System.currentTimeMillis());
            collectionUserMonyService.insertCollectionUserMony(income);
            Double yesMoney = yesIndex + money;
            openIdMapper.updateYesMoney(id, yesMoney);
            money = index - money;
            openIdMapper.updateNotMoney(id, money);
        }

    }

}
